@{
    ViewData["Title"] = "赋码管理";
    Layout = null;
}

<!-- 直接引入所有必要的CSS和JS文件 -->
<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
<!-- 添加QR码生成库的CDN引用 -->
<script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<!-- 自定义样式 -->
<style>
    body {
        margin: 0;
        padding: 20px;
        background: #f6f8fa;
        font-family: 'Microsoft YaHei', 'PingFang SC', Arial, sans-serif;
    }
    
    .container {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        overflow: hidden;
        max-width: 1200px;
        margin: 0 auto;
    }
    
    .search-area {
        padding: 24px;
        background: #fff;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .search-form .layui-form-item {
        margin-bottom: 15px;
    }
    
    .search-form .layui-form-label {
        width: 90px;
        text-align: right;
        font-size: 14px;
        color: #333;
        font-weight: 500;
    }
    
    .search-form .layui-input-block {
        margin-left: 110px;
    }
    
    .search-form .layui-input,
    .search-form .layui-select,
    .add-form .layui-input,
    .add-form .layui-select,
    .add-form .layui-textarea {
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        height: 38px;
        line-height: 38px;
        padding: 0 12px;
        background: #fcfcfc;
        transition: all 0.3s;
    }
    
    .search-form .layui-input:focus,
    .search-form .layui-select:focus,
    .add-form .layui-input:focus,
    .add-form .layui-select:focus,
    .add-form .layui-textarea:focus {
        border-color: #1e9fff;
        box-shadow: 0 0 4px rgba(30,159,255,0.2);
    }
    
    .search-buttons {
        text-align: center;
        margin-top: 20px;
    }
    
    .search-buttons .layui-btn {
        min-width: 90px;
        border-radius: 4px;
        font-size: 14px;
        transition: all 0.3s;
        margin: 0 6px;
    }
    
    .content-area {
        padding: 24px;
        background: #fff;
    }
    
    .toolbar {
        margin-bottom: 16px;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
    
    .toolbar .layui-btn {
        border-radius: 4px;
        font-size: 14px;
        padding: 0 16px;
        transition: all 0.3s;
    }
    
    /* 表格样式 */
    .layui-table {
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        overflow: hidden;
    }
    
    .layui-table th {
        background: #fafafa;
        color: #333;
        font-weight: 600;
        border-bottom: 1px solid #eee;
        padding: 14px 10px;
        font-size: 14px;
        text-align: center;
        vertical-align: middle;
    }
    
    .layui-table td {
        border-bottom: 1px solid #f5f5f5;
        padding: 12px 10px;
        font-size: 14px;
        text-align: center;
        vertical-align: middle;
        line-height: 1.5;
    }
    
    /* 斑马线效果 */
    .layui-table tbody tr:nth-child(even) {
        background-color: #fcfcfc;
    }
    
    /* 鼠标悬停效果 */
    .layui-table tbody tr:hover {
        background-color: #f3f9ff;
        transition: background-color 0.2s ease;
    }

    /* 修复表格边框 */
    .layui-table-view {
        margin: 0;
        border-radius: 4px;
        overflow: hidden;
    }

    /* 调整表格文字垂直对齐和间距 */
    .layui-table-cell {
        height: auto;
        line-height: 1.5;
        padding: 12px 10px;
        position: relative;
        box-sizing: border-box;
        vertical-align: middle;
        word-wrap: break-word;
        word-break: break-all;
    }
    
    /* 表格头部样式优化 */
    .layui-table thead tr {
        background: linear-gradient(135deg, #fafafa 0%, #f4f4f4 100%);
    }
    
    .layui-table th .layui-table-cell {
        font-weight: 600;
        color: #333;
        text-align: center;
        padding: 14px 10px;
    }
    
    /* 表格内容区域样式 */
    .layui-table tbody td {
        border-right: 1px solid #f8f8f8;
    }
    
    .layui-table tbody td:last-child {
        border-right: none;
    }
    
    /* 条码字段特殊样式 */
    .layui-table tbody td[data-field="barCode"] {
        font-family: 'Courier New', monospace;
        font-weight: 500;
        color: #2c3e50;
        background-color: #f8f9fa;
    }
    
    /* 条码格式标签样式 */
    .layui-table tbody td[data-field="barFormat"] .layui-table-cell {
        font-weight: 500;
    }
    
    .layui-table tbody td[data-field="barFormat"] .layui-table-cell:contains("QR二维码") {
        color: #1e9fff;
    }
    
    .layui-table tbody td[data-field="barFormat"] .layui-table-cell:contains("EAN码") {
        color: #ff5722;
    }
    
    .layui-table tbody td[data-field="barFormat"] .layui-table-cell:contains("UPC码") {
        color: #ff9800;
    }
    
    /* 状态字段样式 */
    .layui-table tbody td[data-field="isNo"] .layui-table-cell {
        font-weight: 500;
    }
    
    .layui-table tbody td[data-field="isNo"] .layui-table-cell:contains("是") {
        color: #009688;
    }
    
    .layui-table tbody td[data-field="isNo"] .layui-table-cell:contains("否") {
        color: #FF5722;
    }
    
    /* 操作按钮样式 */
    .table-actions {
        display: flex;
        gap: 8px;
        justify-content: center;
        align-items: center;
    }
    
    .table-actions .layui-btn {
        padding: 6px 12px;
        height: 30px;
        line-height: 18px;
        font-size: 13px;
        border-radius: 4px;
        transition: all 0.2s ease;
    }
    
    .table-actions .layui-btn:hover {
        opacity: 0.9;
    }
    
    .btn-view {
        background: #1e9fff;
        border-color: #1e9fff;
    }
    
    .btn-view:hover {
        background: #0d8ae6;
        border-color: #0d8ae6;
    }
    
    .btn-edit {
        background: #ffb800;
        border-color: #ffb800;
    }
    
    .btn-edit:hover {
        background: #e6a600;
        border-color: #e6a600;
    }
    
    .btn-delete {
        background: #ff5722;
        border-color: #ff5722;
    }
    
    .btn-delete:hover {
        background: #e64a19;
        border-color: #e64a19;
    }
    
    /* 表格中无数据时的样式 */
    .layui-none {
        padding: 40px 0;
        color: #999;
        font-size: 14px;
        text-align: center;
        background: #fafafa;
    }
    
    /* 表格容器样式 */
    .layui-table-view .layui-table {
        margin: 0;
        border-collapse: separate;
        border-spacing: 0;
    }
    
    /* 表格响应式处理 */
    @@media (max-width: 768px) {
        .container {
            border-radius: 6px;
        }
        
        .search-area, .content-area {
            padding: 16px;
        }
        
        .search-form .layui-form-label {
            width: 80px;
        }
        
        .search-form .layui-input-block {
            margin-left: 100px;
        }
        
        .layui-table th,
        .layui-table td {
            padding: 10px 6px;
            font-size: 13px;
        }
        
        .table-actions .layui-btn {
            padding: 4px 10px;
            height: 28px;
            line-height: 18px;
            font-size: 12px;
        }
    }
    
    @@media (max-width: 576px) {
        .container {
            border-radius: 4px;
        }
        
        .search-area, .content-area {
            padding: 12px 10px;
        }
        
        .search-form .layui-form-label {
            width: 70px;
            font-size: 13px;
        }
        
        .search-form .layui-input-block {
            margin-left: 80px;
        }
        
        .toolbar {
            flex-direction: column;
            gap: 8px;
        }
        
        .toolbar .layui-btn {
            width: 100%;
        }
    }

    /* 添加表单样式 */
    .add-form .layui-form-label {
        width: 100px;
        font-weight: 500;
    }
    
    .add-form .layui-input-block {
        margin-left: 130px;
    }
    
    .add-form .required {
        color: #FF5722;
        margin-right: 2px;
    }
    
    .add-form .layui-form-item {
        margin-bottom: 18px;
    }
    
    .add-form .layui-textarea {
        min-height: 80px;
        resize: vertical;
    }
    
    .barcode-container {
        min-height: 80px;
        background-color: #fcfcfc;
        padding: 18px;
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        text-align: center;
    }
    
    .barcode-preview {
        margin-top: 16px;
        margin-bottom: 20px;
    }
    
    #barcodeLabel {
        font-size: 15px;
        font-weight: bold;
        margin-bottom: 12px;
        color: #1e9fff;
    }
    
    #barcodeDisplay {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 150px;
        background: #fcfcfc;
        padding: 10px;
        border-radius: 4px;
    }
    
    #barcodeDisplay img {
        max-width: 100%;
        height: auto;
        border: 1px solid #eee;
        border-radius: 4px;
        padding: 4px;
    }
    
    /* 弹出层样式优化 */
    .layui-layer {
        border-radius: 4px !important;
        box-shadow: 0 2px 16px rgba(0, 0, 0, 0.1) !important;
    }
    
    .layui-layer-title {
        background: #fff !important;
        border-bottom: 1px solid #f0f0f0 !important;
        font-weight: 600 !important;
        color: #333 !important;
        height: 50px !important;
        line-height: 50px !important;
        font-size: 16px !important;
    }
    
    .layui-layer-btn {
        padding: 15px !important;
        text-align: center !important;
        border-top: 1px solid #f0f0f0 !important;
    }
    
    .layui-layer-btn a {
        border-radius: 4px !important;
        transition: all 0.2s !important;
    }
    
    /* 表单按钮行容器 */
    .form-actions {
        text-align: center;
        margin-top: 30px;
        display: flex;
        justify-content: center;
        gap: 15px;
    }
    
    .form-actions .layui-btn {
        min-width: 90px;
        padding: 0 25px;
        border-radius: 4px;
        transition: all 0.2s;
    }
    
    /* 全局按钮悬浮效果 */
    .layui-btn:hover {
        opacity: 0.9;
        transform: translateY(-1px);
    }
    
    /* 页脚样式 */
    .footer {
        text-align: center;
        padding: 15px;
        color: #999;
        font-size: 12px;
    }
</style>

<div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
        <form class="layui-form search-form" lay-filter="searchForm" id="searchForm">
            <div class="layui-row">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">条码类型</label>
                        <div class="layui-input-block">
                            <select name="barTypes">
                                <option value="">请选择条码类型</option>
                                <option value="产品条码">产品条码</option>
                                <option value="包装条码">包装条码</option>
                                <option value="批次条码">批次条码</option>
                                <option value="序列号条码">序列号条码</option>
                                <option value="位置条码">位置条码</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">业务编码</label>
                        <div class="layui-input-block">
                            <input type="text" name="businessCode" placeholder="请输入业务编码" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">业务名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="businessName" placeholder="请输入业务名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="search-buttons">
                <button type="button" class="layui-btn" lay-submit lay-filter="search">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button type="reset" class="layui-btn layui-btn-primary">
                    <i class="layui-icon layui-icon-refresh"></i> 重置
                </button>
            </div>
        </form>
    </div>
    
    <!-- 内容区域 -->
    <div class="content-area">
        <!-- 工具栏 -->
        <div class="toolbar">
            <button type="button" class="layui-btn" id="addBtn">
                <i class="layui-icon layui-icon-add-1"></i> 新增
            </button>
            <button type="button" class="layui-btn layui-btn-normal" id="refreshBtn">
                <i class="layui-icon layui-icon-refresh-3"></i> 刷新
            </button>
        </div>
        
        <!-- 数据表格 -->
        <table class="layui-hide" id="codingmanagementTable" lay-filter="codingmanagementTable"></table>
    </div>
</div>

<!-- 表格操作按钮模板 -->
<script type="text/html" id="actionTpl">
    <div class="table-actions">
        <button class="layui-btn layui-btn-xs btn-view" lay-event="view" title="查看详情">
            <i class="layui-icon layui-icon-search"></i> 查看
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-danger btn-delete" lay-event="delete" title="删除记录">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </button>
    </div>
</script>

<!-- 添加条码的表单模板 -->
<script type="text/html" id="addFormTpl">
    <form class="layui-form add-form" lay-filter="addForm" style="padding: 20px 30px 0 0;">
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>条码格式</label>
            <div class="layui-input-block">
                <select name="barFormat" lay-filter="barFormat" lay-verify="required">
                    <option value="">请选择条码格式</option>
                    <option value="QR二维码">QR二维码</option>
                    <option value="EAN码">EAN码</option>
                    <option value="UPC码">UPC码</option>
                </select>
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>条码类型</label>
            <div class="layui-input-block">
                <select name="barTypes" lay-filter="barTypes" lay-verify="required">
                    <option value="">请选择条码类型</option>
                    <option value="产品条码">产品条码</option>
                    <option value="包装条码">包装条码</option>
                    <option value="批次条码">批次条码</option>
                    <option value="序列号条码">序列号条码</option>
                    <option value="位置条码">位置条码</option>
                    <option value="其他">其他</option>
                </select>
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>是否启用</label>
            <div class="layui-input-block">
                <input type="radio" name="isNo" value="是" title="是" checked>
                <input type="radio" name="isNo" value="否" title="否">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">条码内容</label>
            <div class="layui-input-block">
                <textarea name="barContext" placeholder="请输入条码内容" class="layui-textarea" id="barContextInput"></textarea>
            </div>
        </div>
        
        <div class="layui-form-item barcode-preview" style="display:none;">
            <label class="layui-form-label">条码预览</label>
            <div class="layui-input-block">
                <div id="barcodePreview" class="barcode-container">
                    <div id="barcodeLabel"></div>
                    <div id="barcodeDisplay"></div>
                    <div class="barcode-tip" style="margin-top: 10px; color: #999; font-size: 12px;">手机扫描可获取条码信息</div>
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>条码</label>
            <div class="layui-input-block">
                <input type="text" name="barCode" lay-verify="required" placeholder="请输入条码" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>业务编码</label>
            <div class="layui-input-block">
                <input type="text" name="businessCode" lay-verify="required" placeholder="请输入业务编码" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="required">*</span>业务名称</label>
            <div class="layui-input-block">
                <input type="text" name="businessName" lay-verify="required" placeholder="请输入业务名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>
        
        <div class="form-actions">
            <button type="button" class="layui-btn layui-btn-normal" lay-submit lay-filter="formSubmit">保存</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
        </div>
    </form>
</script>

<script>
layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table,
        form = layui.form,
        layer = layui.layer,
        $ = layui.$;
    
    // 测试QRCode库是否正常工作
    console.log('QRCode库状态:', typeof QRCode);
    
    // 渲染表格
    table.render({
        elem: '#codingmanagementTable',
        url: '/WarehouseManagement/Codingmanagement/GetCodingmanagements',
        toolbar: false,
        defaultToolbar: [],
        cols: [[
            {field: 'barCode', title: '条码', width: 140, align: 'center'},
            {field: 'barFormat', title: '条码格式', width: 110, align: 'center'},
            {field: 'barTypes', title: '条码类型', width: 110, align: 'center'},
            {field: 'barContext', title: '条码内容', width: 180, align: 'center'},
            {field: 'businessCode', title: '业务编码', width: 130, align: 'center'},
            {field: 'businessName', title: '业务名称', minWidth: 150, align: 'center'},
            {field: 'isNo', title: '是否生效', width: 100, align: 'center'},
            {fixed: 'right', title: '操作', toolbar: '#actionTpl', width: 180, align: 'center'}
        ]],
        page: true,
        limit: 10,
        limits: [10, 20, 50, 100],
        loading: true,
        even: true,
        cellMinWidth: 80,
        skin: 'line',
        lineStyle: 'height: 50px',
        size: 'sm',
        text: {
            none: '暂无相关数据'
        },
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        response: {
            statusName: 'code',
            statusCode: 0,
            msgName: 'msg',
            countName: 'count',
            dataName: 'data'
        },
        parseData: function(res) {
            // 添加数据检查，确保返回的数据格式正确
            if(!res || typeof res !== 'object') {
                console.error('接收到无效的数据格式');
                return {
                    "code": 1,
                    "msg": "服务器返回数据格式错误",
                    "count": 0,
                    "data": []
                };
            }
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count || 0,
                "data": res.data || []
            };
        },
        error: function(res) {
            console.error('表格加载失败', res);
            layer.msg('表格数据加载失败，请刷新页面重试');
        }
    });
    
    // 搜索功能
    form.on('submit(search)', function(data){
        // 搜索前检查数据格式
        var formData = data.field;
        
        // 记录搜索参数
        console.log('搜索参数：', formData);
        
        table.reload('codingmanagementTable', {
            url: '/WarehouseManagement/Codingmanagement/GetCodingmanagements',
            where: formData,
            page: {
                curr: 1
            }
        });
        return false;
    });
    
    // 重置按钮事件
    $('#searchForm button[type="reset"]').click(function() {
        // 重置后自动刷新表格
        setTimeout(function() {
            table.reload('codingmanagementTable', {
                where: {},
                page: {
                    curr: 1
                }
            });
        }, 100);
    });
    
    // 新增按钮
    $('#addBtn').click(function() {
        layer.open({
            type: 1,
            title: '添加条码',
            area: ['650px', '650px'],
            content: $('#addFormTpl').html(),
            success: function(layero, index) {
                form.render(); // 重新渲染表单元素
                
                // 监听条码格式选择
                form.on('select(barFormat)', function(data) {
                    updateBarcodePreview(data.value, $('#barContextInput').val());
                    
                    // 自动生成随机条码数据供参考
                    var example = generateSampleBarcodeData(data.value);
                    if(example && $('#barContextInput').val() === '') {
                        $('#barContextInput').val(example);
                        updateBarcodePreview(data.value, example);
                    }
                });
                
                // 监听条码内容输入
                $('#barContextInput').on('input', function() {
                    var barFormat = $('select[name="barFormat"]').val();
                    updateBarcodePreview(barFormat, $(this).val());
                });
                
                // 监听取消按钮
                $('#cancelBtn').click(function() {
                    layer.close(index);
                });
                
                // 监听表单提交
                form.on('submit(formSubmit)', function(data) {
                    var formData = data.field;
                    console.log('表单数据：', formData);
                    
                    // 使用Ajax提交表单
                    $.ajax({
                        url: '/WarehouseManagement/Codingmanagement/Add',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('添加成功', {icon: 1});
                                layer.close(index);
                                table.reload('codingmanagementTable'); // 刷新表格
                            } else {
                                layer.msg('添加失败：' + res.msg, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('服务器异常，请稍后重试', {icon: 2});
                        }
                    });
                    
                    return false; // 阻止表单默认提交
                });
            }
        });
    });
    
    // 刷新按钮
    $('#refreshBtn').click(function() {
        table.reload('codingmanagementTable');
    });
    
    // 监听行工具事件
    table.on('tool(codingmanagementTable)', function(obj) {
        var data = obj.data;
        if (obj.event === 'view') {
            // 查看功能
            showViewDialog(data);
        } else if (obj.event === 'delete') {
            // 删除功能
            layer.confirm('确定要删除这条记录吗？', {
                icon: 3,
                title: '删除确认',
                btn: ['确定', '取消']
            }, function(index) {
                // 确定删除
                deleteRecord(data.id, index);
            });
        }
    });

    // 显示查看对话框
    function showViewDialog(data) {
        var content = '<div style="padding: 20px; line-height: 2;">';
        content += '<div><strong>条码：</strong>' + (data.barCode || '') + '</div>';
        content += '<div><strong>条码格式：</strong>' + (data.barFormat || '') + '</div>';
        content += '<div><strong>条码类型：</strong>' + (data.barTypes || '') + '</div>';
        content += '<div><strong>条码内容：</strong>' + (data.barContext || '') + '</div>';
        content += '<div><strong>业务编码：</strong>' + (data.businessCode || '') + '</div>';
        content += '<div><strong>业务名称：</strong>' + (data.businessName || '') + '</div>';
        content += '<div><strong>是否生效：</strong>' + (data.isNo || '') + '</div>';
        
        // 如果有条码内容，显示条码预览
        if (data.barContext && data.barFormat) {
            content += '<div style="margin-top: 20px;"><strong>条码预览：</strong></div>';
            content += '<div id="viewBarcodeDisplay" style="text-align: center; margin-top: 10px; padding: 20px; border: 1px solid #ddd; background: #f9f9f9;">';
            content += '正在生成条码预览...';
            content += '</div>';
        }
        
        content += '</div>';
        
        layer.open({
            type: 1,
            title: '查看赋码信息',
            area: ['500px', 'auto'],
            content: content,
            success: function(layero, index) {
                // 生成条码预览
                if (data.barContext && data.barFormat) {
                    generateViewBarcode(data.barFormat, data.barContext);
                }
            }
        });
    }
    
    // 生成查看页面的条码预览（只保留本地二维码生成）
    function generateViewBarcode(barFormat, barContent) {
        try {
            if (barFormat === 'QR二维码') {
                $('#viewBarcodeDisplay').html('<div id="qrcode_local_view" style="display: flex; justify-content: center; align-items: center;"></div>');
                if (typeof QRCode !== 'undefined') {
                    new QRCode(document.getElementById('qrcode_local_view'), {
                        text: barContent,
                        width: 150,
                        height: 150,
                        colorDark: "#000000",
                        colorLight: "#ffffff"
                    });
                } else {
                    $('#qrcode_local_view').html('<div style="width: 150px; height: 150px; border: 2px solid #ddd; display: flex; align-items: center; justify-content: center; background: #f9f9f9; font-size: 14px; color: #666;">二维码内容:<br/>' + barContent + '</div>');
                }
            } else {
                // 其它条码类型逻辑不变（可按需保留或优化）
            }
        } catch (e) {
            $('#viewBarcodeDisplay').html('<div style="color: #f00; text-align: center;">二维码生成失败</div>');
        }
    }
    
    // 生成主页面的二维码预览（只保留本地二维码生成）
    function generateLocalQRCode(text) {
        try {
            $('#barcodeDisplay').html('<div id="qrcode_local_' + Date.now() + '" style="display: flex; justify-content: center; align-items: center;"></div>');
            var qrContainer = $('#barcodeDisplay').find('div')[0];
            if (typeof QRCode !== 'undefined') {
                new QRCode(qrContainer, {
                    text: text,
                    width: 160,
                    height: 160,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel ? QRCode.CorrectLevel.H : 2
                });
            } else {
                qrContainer.innerHTML = '<div style="width: 160px; height: 160px; border: 2px solid #ddd; display: flex; align-items: center; justify-content: center; background: #f9f9f9; font-size: 12px; text-align: center; color: #666; word-wrap: break-word; padding: 10px;">二维码内容:<br/>' + text.substring(0, 30) + (text.length > 30 ? '...' : '') + '</div>';
            }
        } catch (e) {
            $('#barcodeDisplay').html('<div style="color: #f00; padding: 10px;">二维码生成失败</div>');
        }
    }
    
    // 删除记录
    function deleteRecord(id, layerIndex) {
        $.ajax({
            url: '/WarehouseManagement/Codingmanagement/Delete/' + id,
            type: 'POST',
            success: function(res) {
                if (res.code === 0) {
                    layer.msg('删除成功', {icon: 1});
                    layer.close(layerIndex);
                    table.reload('codingmanagementTable'); // 刷新表格
                } else {
                    layer.msg('删除失败：' + res.msg, {icon: 2});
                }
            },
            error: function() {
                layer.msg('服务器异常，请稍后重试', {icon: 2});
            }
        });
    }

    // 更新条码预览
    function updateBarcodePreview(barFormat, barContent) {
        if (!barFormat) {
            $('.barcode-preview').hide();
            return;
        }
        // 显示预览区域
        $('.barcode-preview').show();
        // 设置标签
        $('#barcodeLabel').text(barFormat);
        if (!barContent) {
            $('#barcodeDisplay').html('<div style="color: #999; padding: 10px;">请输入条码内容以预览</div>');
            return;
        }
        try {
            var previewHtml = '';
            if (barFormat === 'QR二维码') {
                // 使用在线API生成二维码
                var qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=' + encodeURIComponent(barContent);
                previewHtml = '<div style="text-align: center;">';
                previewHtml += '<img src="' + qrApiUrl + '" alt="二维码" style="width: 160px; height: 160px; border: 1px solid #ddd;" onerror="this.style.display=\'none\'; this.nextSibling.style.display=\'block\';">';
                previewHtml += '<div style="display: none; width: 160px; height: 160px; border: 2px solid #ddd; background: #f9f9f9; line-height: 160px; text-align: center; color: #666; font-size: 12px; margin: 0 auto;">二维码生成失败</div>';
                previewHtml += '</div>';
                $('#barcodeDisplay').html(previewHtml);
                
                // 备用方案：如果在线API失败，使用本地生成
                setTimeout(function() {
                    var img = $('#barcodeDisplay img')[0];
                    if (img && img.complete && img.naturalWidth === 0) {
                        // 图片加载失败，使用本地生成
                        generateLocalQRCode(barContent);
                    }
                }, 2000);
                
            } else if (barFormat === 'EAN码') {
                // 验证并格式化EAN码
                var validEAN = validateAndFormatEAN(barContent);
                
                // 使用多个API备用方案生成EAN码
                var eanApiUrls = [
                    'https://barcodeapi.org/api/ean13/' + encodeURIComponent(validEAN),
                    'https://api.qrserver.com/v1/create-barcode/?size=200x80&data=' + encodeURIComponent(validEAN) + '&type=ean13',
                    'https://barcode.tec-it.com/barcode.ashx?data=' + encodeURIComponent(validEAN) + '&code=EAN13&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0'
                ];
                
                previewHtml = '<div style="text-align: center;">';
                previewHtml += '<div style="font-size: 12px; margin-bottom: 5px; color: #666;">EAN-13条码</div>';
                previewHtml += '<img src="' + eanApiUrls[0] + '" alt="EAN码" style="width: 200px; height: 80px; border: 1px solid #ddd;" onerror="tryNextEANAPI(this, [\'' + eanApiUrls.join('\',\'') + '\'], \'' + validEAN + '\', 0)">';
                previewHtml += '<div style="font-size: 12px; margin-top: 5px; color: #333;">' + validEAN + '</div>';
                previewHtml += '</div>';
                $('#barcodeDisplay').html(previewHtml);
                
            } else if (barFormat === 'UPC码') {
                // 验证并格式化UPC码
                var validUPC = validateAndFormatUPC(barContent);
                
                // 使用多个API备用方案生成UPC码
                var upcApiUrls = [
                    'https://barcodeapi.org/api/upca/' + encodeURIComponent(validUPC),
                    'https://api.qrserver.com/v1/create-barcode/?size=180x80&data=' + encodeURIComponent(validUPC) + '&type=upca',
                    'https://barcode.tec-it.com/barcode.ashx?data=' + encodeURIComponent(validUPC) + '&code=UPCA&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0'
                ];
                
                previewHtml = '<div style="text-align: center;">';
                previewHtml += '<div style="font-size: 12px; margin-bottom: 5px; color: #666;">UPC-A条码</div>';
                previewHtml += '<img src="' + upcApiUrls[0] + '" alt="UPC码" style="width: 180px; height: 80px; border: 1px solid #ddd;" onerror="tryNextUPCAPI(this, [\'' + upcApiUrls.join('\',\'') + '\'], \'' + validUPC + '\', 0)">';
                previewHtml += '<div style="font-size: 12px; margin-top: 5px; color: #333;">' + validUPC + '</div>';
                previewHtml += '</div>';
                $('#barcodeDisplay').html(previewHtml);
                
            } else {
                // 默认使用二维码显示所有内容
                var qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=' + encodeURIComponent(barContent);
                previewHtml = '<div style="text-align: center;">';
                previewHtml += '<img src="' + qrApiUrl + '" alt="二维码" style="width: 120px; height: 120px; border: 1px solid #ddd;" onerror="this.style.display=\'none\'; this.nextSibling.style.display=\'block\';">';
                previewHtml += '<div style="display: none; width: 120px; height: 120px; border: 2px solid #ddd; background: #f9f9f9; line-height: 120px; text-align: center; color: #666; font-size: 12px; margin: 0 auto;">二维码生成失败</div>';
                previewHtml += '</div>';
                $('#barcodeDisplay').html(previewHtml);
            }
        } catch (e) {
            console.error('条码生成错误', e);
            $('#barcodeDisplay').html('<div style="color: #f00; padding: 10px;">条码生成失败，请检查内容格式</div>');
        }
    }
    
    // 尝试下一个EAN API
    function tryNextEANAPI(imgElement, apiUrls, eanCode, currentIndex) {
        currentIndex++;
        if (currentIndex < apiUrls.length) {
            imgElement.src = apiUrls[currentIndex];
            imgElement.onerror = function() {
                tryNextEANAPI(imgElement, apiUrls, eanCode, currentIndex);
            };
        } else {
            // 所有API都失败，使用备用显示
            generateFallbackEAN(eanCode);
        }
    }
    
    // 尝试下一个UPC API
    function tryNextUPCAPI(imgElement, apiUrls, upcCode, currentIndex) {
        currentIndex++;
        if (currentIndex < apiUrls.length) {
            imgElement.src = apiUrls[currentIndex];
            imgElement.onerror = function() {
                tryNextUPCAPI(imgElement, apiUrls, upcCode, currentIndex);
            };
        } else {
            // 所有API都失败，使用备用显示
            generateFallbackUPC(upcCode);
        }
    }
    
    // 生成备用EAN码显示
    function generateFallbackEAN(eanCode) {
        var fallbackHtml = '<div style="text-align: center;">';
        fallbackHtml += '<div style="font-size: 12px; margin-bottom: 5px; color: #666;">EAN-13条码</div>';
        fallbackHtml += '<div style="width: 200px; height: 80px; margin: 0 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; border: 1px solid #ddd; background: #fff;">';
        fallbackHtml += '<div style="width: 180px; height: 50px; background: repeating-linear-gradient(90deg, #000 0px, #000 1px, #fff 1px, #fff 2px, #000 2px, #000 3px, #fff 3px, #fff 5px); display: flex; align-items: center; justify-content: center;">';
        fallbackHtml += '<span style="background: #fff; padding: 2px 4px; font-size: 10px; color: #000;">EAN</span>';
        fallbackHtml += '</div>';
        fallbackHtml += '</div>';
        fallbackHtml += '<div style="font-size: 12px; margin-top: 5px; color: #333;">' + eanCode + '</div>';
        fallbackHtml += '<div style="font-size: 10px; color: #999; margin-top: 2px;">备用显示 - 建议使用专业条码扫描器</div>';
        fallbackHtml += '</div>';
        $('#barcodeDisplay').html(fallbackHtml);
    }
    
    // 生成备用UPC码显示
    function generateFallbackUPC(upcCode) {
        var fallbackHtml = '<div style="text-align: center;">';
        fallbackHtml += '<div style="font-size: 12px; margin-bottom: 5px; color: #666;">UPC-A条码</div>';
        fallbackHtml += '<div style="width: 180px; height: 80px; margin: 0 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; border: 1px solid #ddd; background: #fff;">';
        fallbackHtml += '<div style="width: 160px; height: 50px; background: repeating-linear-gradient(90deg, #000 0px, #000 1px, #fff 1px, #fff 2px, #000 2px, #000 3px, #fff 3px, #fff 4px); display: flex; align-items: center; justify-content: center;">';
        fallbackHtml += '<span style="background: #fff; padding: 2px 4px; font-size: 10px; color: #000;">UPC</span>';
        fallbackHtml += '</div>';
        fallbackHtml += '</div>';
        fallbackHtml += '<div style="font-size: 12px; margin-top: 5px; color: #333;">' + upcCode + '</div>';
        fallbackHtml += '<div style="font-size: 10px; color: #999; margin-top: 2px;">备用显示 - 建议使用专业条码扫描器</div>';
        fallbackHtml += '</div>';
        $('#barcodeDisplay').html(fallbackHtml);
    }
    
    // 验证并格式化EAN码
    function validateAndFormatEAN(input) {
        // 移除非数字字符
        var digits = input.replace(/\D/g, '');
        
        // 如果输入为空，生成示例EAN码
        if (digits.length === 0) {
            digits = '123456789012';
        }
        
        // 确保至少有12位数字
        if (digits.length < 12) {
            // 补足位数
            while (digits.length < 12) {
                digits = '0' + digits;
            }
        }
        
        // 如果超过13位，截取前12位
        if (digits.length > 13) {
            digits = digits.substring(0, 12);
        } else if (digits.length === 13) {
            // 如果是13位，取前12位重新计算校验位
            digits = digits.substring(0, 12);
        }
        
        // 计算EAN-13校验位
        var checksum = calculateEANChecksum(digits);
        
        return digits + checksum;
    }
    
    // 计算EAN-13校验位
    function calculateEANChecksum(digits) {
        var sum = 0;
        for (var i = 0; i < 12; i++) {
            var digit = parseInt(digits.charAt(i));
            if (i % 2 === 0) {
                sum += digit;
            } else {
                sum += digit * 3;
            }
        }
        var checksum = (10 - (sum % 10)) % 10;
        return checksum.toString();
    }
    
    // 验证并格式化UPC码
    function validateAndFormatUPC(input) {
        // 移除非数字字符
        var digits = input.replace(/\D/g, '');
        
        // 如果输入为空，生成示例UPC码
        if (digits.length === 0) {
            digits = '12345678901';
        }
        
        // 确保至少有11位数字
        if (digits.length < 11) {
            // 补足位数
            while (digits.length < 11) {
                digits = '0' + digits;
            }
        }
        
        // 如果超过12位，截取前11位
        if (digits.length > 12) {
            digits = digits.substring(0, 11);
        } else if (digits.length === 12) {
            // 如果是12位，取前11位重新计算校验位
            digits = digits.substring(0, 11);
        }
        
        // 计算UPC-A校验位
        var checksum = calculateUPCChecksum(digits);
        
        return digits + checksum;
    }
    
    // 计算UPC-A校验位
    function calculateUPCChecksum(digits) {
        var sum = 0;
        for (var i = 0; i < 11; i++) {
            var digit = parseInt(digits.charAt(i));
            if (i % 2 === 0) {
                sum += digit * 3;
            } else {
                sum += digit;
            }
        }
        var checksum = (10 - (sum % 10)) % 10;
        return checksum.toString();
    }
    
    // 生成示例条码数据
    function generateSampleBarcodeData(barFormat) {
        if (barFormat === 'QR二维码') {
            return 'https://example.com/product/12345';
        } else if (barFormat === 'EAN码') {
            // 生成12位随机数字
            return generateRandomDigits(12);
        } else if (barFormat === 'UPC码') {
            // 生成11位随机数字
            return generateRandomDigits(11);
        }
        return '';
    }
    
    // 生成指定长度的随机数字
    function generateRandomDigits(length) {
        var result = '';
        for (var i = 0; i < length; i++) {
            result += Math.floor(Math.random() * 10);
        }
        return result;
    }
});
</script> 